import React, { useState, useEffect } from 'react';
import { Tree, Input, Modal, Form, Select, Radio } from 'antd';
import './organization.less';
import {
  EditOutlined,
  MinusCircleOutlined,
  PlusCircleOutlined,
  UpCircleOutlined,
  DownCircleOutlined,
} from '@ant-design/icons';
import { nanoid } from 'nanoid';
export default function () {
  const [form] = Form.useForm();
  const { Search } = Input;
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [dataList, setDataList] = useState([]);
  const [showLine, setShowLine] = useState({
    showLeafIcon: false,
  });
  const [keys, setKeys] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [allName, setAllName] = useState('');
  const [parent, setParent] = useState('');
  const [isEdit, setIsEdit] = useState('');
  const [gData, setgData] = useState([
    {
      title: '集体',
      key: '0',
      myShow: false,
      children: [
        {
          title: '物流组',
          key: '0-0',

          myShow: false,
        },
        {
          title: '总经办',
          key: '0-1',

          myShow: false,
        },
        {
          title: '门店',
          key: '0-2',

          myShow: false,
          children: [
            {
              title: '服务组',
              key: '0-0-0',
              myShow: false,
            },
            {
              title: '厨房',
              key: '0-0-1',
              myShow: false,
            },
          ],
        },
      ],
    },
    {
      title: 'DT组',
      key: '1',

      myShow: false,
    },
    {
      title: '财务组',
      key: '2',

      myShow: false,
    },
    {
      title: '运营组',
      key: '3',

      myShow: false,
    },
    {
      title: '培训组',
      key: '4',

      myShow: false,
    },
    {
      title: '企业组',
      key: '5',

      myShow: false,
    },
  ]);
  const { TextArea } = Input;
  const { Option } = Select;

  const addClick = (e) => {
    // console.log(cycleAddtFn(gData, e.key));
    form.setFieldsValue({ higherOffice: cycleAddtFn(gData, e.key) });

    setIsEdit(false);
    setIsModalVisible(true);
  };
  const cycleAddtFn = (arr, key) => {
    let k;
    function aaa(arr, key) {
      if (arr.some((i) => i.key == key)) {
        k = arr.find((i) => i.key == key);
        return k?.title;
      } else {
        arr.forEach((i) => {
          if (i.children && i.children.length) {
            aaa(i.children, key);
          }
        });
      }
      return k?.title;
    }
    return aaa(arr, key);
  };

  const cycleParent = (arr, key) => {
    let pararr = '';
    function bbb(arr, key, b) {
      let a = [...arr];
      // console.log(a, key);
      if (a.map((item) => item.key).includes(key)) {
        if (b) {
          pararr = b;
        }
        return pararr;
      } else {
        a.forEach((item) => {
          if (item.children) {
            return bbb(item.children, key, item.title);
          }
        });
      }
      return pararr;
    }
    return bbb(arr, key);
  };

  const upClick = (e) => {
    cycleUpFn(gData, e.key);
  };
  const downClick = (e) => {
    cycleDownFn(gData, e.key);
  };
  const cycleDownFn = (arr, key) => {
    if (arr.some((i) => i.key == key)) {
      let k = arr.findIndex((i) => i.key == key);

      let UponItem = arr[k + 1];
      arr.splice(k + 1, 1);
      arr.splice(k, 0, UponItem);
    } else {
      arr.forEach((i) => {
        if (i.children && i.children.length)
          return cycleDownFn(i.children, key);
      });
    }

    return arr;
  };

  const onExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e) => {
    const { value } = e.target;
    const expandedKeys = dataList
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, gData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);

    setExpandedKeys(expandedKeys);
    setSearchValue(value);
    setAutoExpandParent(true);
  };
  const onSelect = (selectedKeys, info) => {
    setAllName(cycleAddtFn(gData, info.node.key));
    setParent(cycleParent(gData, info.node.key));

    let a = JSON.parse(
      JSON.stringify(cycleShowFn(gData, info.node.key, info.selected)),
    );

    setgData(a);
  };
  const deletClick = (e) => {
    cycleDeletFn(gData, e.key);
  };

  const cycleDeletFn = (arr, key) => {
    if (arr.some((i) => i.key == key)) {
      let k = arr.findIndex((i) => i.key == key);

      arr.splice(k, 1);
    } else {
      arr.forEach((i) => {
        if (i.children && i.children.length)
          return cycleDeletFn(i.children, key);
      });
    }
    return arr;
  };
  const cycleNameFn = (arr, key) => {
    if (arr.some((i) => i.key == key)) {
      let k = arr.find((i) => i.key == key);
      const { systemName } = form.getFieldValue();
      k.title = systemName;
    } else {
      arr.forEach((i) => {
        if (i.children && i.children.length)
          return cycleNameFn(i.children, key);
      });
    }
    return arr;
  };

  const handleOk = () => {
    if (isEdit) {
      cycleNameFn(gData, keys);
    } else {
      const { higherOffice, systemName } = form.getFieldValue();
      let a = JSON.parse(
        JSON.stringify(cycleOkFn(gData, higherOffice, systemName)),
      );

      setgData(a);
      // console.log(a);
    }

    setIsModalVisible(false);
    form.resetFields();
  };

  const cycleOkFn = (arr, key, systemName) => {
    if (arr.some((i) => i.title == key)) {
      let b = arr.find((i) => i.title == key);
      if (b.children) {
        b.children.push({
          title: systemName,
          key: nanoid(),
        });
      } else {
        b.children = [];
        b.children.push({
          title: systemName,
          key: nanoid(),
        });
      }
    } else {
      arr.forEach((i) => {
        if (i.children && i.children.length)
          return cycleOkFn(i.children, key, systemName);
      });
    }
    return arr;
  };

  const handleCancel = () => {
    form.resetFields();
    setIsModalVisible(false);
  };

  const cycleShowFn = (arr, key, isShow) => {
    if (arr.some((i) => i.key == key)) {
      let b = arr.find((i) => i.key == key);
      b.myShow = isShow;
    } else {
      arr.forEach((i) => {
        if (i.children && i.children.length)
          return cycleShowFn(i.children, key, isShow);
      });
    }
    return arr;
  };

  const cycleUpFn = (arr, key) => {
    if (arr.some((i) => i.key == key)) {
      let k = arr.findIndex((i) => i.key == key);

      let UponItem = arr[k - 1];
      arr.splice(k - 1, 1);
      arr.splice(k, 0, UponItem);
    } else {
      arr.forEach((i) => {
        if (i.children && i.children.length) return cycleUpFn(i.children, key);
      });
    }
    return arr;
  };

  const editClick = (e) => {
    // console.log('111', cycleParent(gData, e.key));
    let a = cycleParent(gData, e.key);
    // console.log(a);
    form.setFieldsValue({
      systemName: cycleAddtFn(gData, e.key),
      higherOffice: a,
    });
    setIsEdit(true);
    setIsModalVisible(true);
    setKeys(e.key);
  };

  const loop = (data) =>
    data.map((item) => {
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substring(0, index);
      const afterStr = item.title.slice(index + searchValue.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span className="site-tree-search-value">{searchValue}</span>
            {afterStr}
          </span>
        ) : (
          <span>{item.title}</span>
        );
      if (item.children) {
        return {
          title,
          key: item.key,
          children: loop(item.children),
          myShow: item.myShow,
        };
      }

      return {
        title,
        key: item.key,
        myShow: item.myShow,
      };
    });
  return (
    <div className="item_content">
      <div className="item_content_left">
        <Search
          style={{ marginBottom: 8 }}
          placeholder="Search"
          onChange={onChange}
        />

        <Tree
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          treeData={loop(gData)}
          showLine={showLine}
          onSelect={onSelect}
          titleRender={(nodeData) => {
            // console.log('*****,', nodeData);
            return (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ marginRight: '10px', color: '#5a5a5a' }}>
                  {nodeData.title}
                </div>
                {nodeData.myShow && (
                  <div>
                    <EditOutlined
                      className="icon-item"
                      onClick={() => {
                        editClick(nodeData);
                      }}
                    />
                    <MinusCircleOutlined
                      className="icon-item"
                      onClick={() => {
                        deletClick(nodeData);
                      }}
                    />
                    <PlusCircleOutlined
                      className="icon-item"
                      onClick={() => {
                        addClick(nodeData);
                      }}
                    />
                    <UpCircleOutlined
                      className="icon-item"
                      onClick={() => {
                        upClick(nodeData);
                      }}
                    />
                    <DownCircleOutlined
                      className="icon-item"
                      onClick={() => {
                        downClick(nodeData);
                      }}
                    />
                  </div>
                )}
              </div>
            );
          }}
        />
        <Modal visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
          <div className="form-all">
            <Form
              form={form}
              autoComplete="off"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 18 }}
            >
              <Form.Item
                label="架构名称"
                name="systemName"
                rules={[{ required: true, message: '请输入架构名称' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="上级部门"
                name="higherOffice"
                rules={[{ required: true, message: '请选择' }]}
              >
                <Select disabled>
                  <Option value="lucy">Lucy</Option>
                </Select>
              </Form.Item>

              <Form.Item
                label="架构类型"
                name="systemType"
                rules={[{ required: true, message: '请选择' }]}
              >
                <Radio.Group>
                  <Radio value={1}>公司</Radio>
                  <Radio value={2}>部门</Radio>
                </Radio.Group>
              </Form.Item>

              <Form.Item label="联系方式" name="connectWay">
                <Input placeholder="请输入手机号码或座机" />
              </Form.Item>

              <Form.Item label="地址" name="address">
                <Input />
              </Form.Item>

              <Form.Item label="备注" name="remark">
                <TextArea placeholder="请输入备注" />
              </Form.Item>
            </Form>
          </div>
        </Modal>
      </div>
      <div className="item_content_right">
        <div>基本信息</div>
        <div className="item-list1">
          <div className="item-list">
            <div className="item-way">
              <div>架构名称：</div>
              <div>{allName}</div>
            </div>
            <div className="item-way">
              <div>上级部门：</div>
              <div>{parent}</div>
            </div>
            <div className="item-way">
              <div>架构类型：</div>
              <div>{'架构类型'}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
